package com.bawei.module_home.ui

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.bawei.library_common.utils.UserUtils
import com.bawei.library_mvi.ui.BaseMviLazyFragment
import com.bawei.module_home.R
import com.bawei.module_home.databinding.HomeFragmentHomeDetailCommentBinding
import com.bawei.module_home.intent.CommentIntent
import com.bawei.module_home.model.entity.CommentEntity
import com.bawei.module_home.model.entity.SimpleVideoEntity
import com.bawei.module_home.state.CommentState
import com.bawei.module_home.viewmodel.CommentViewModel
import com.bawei.module_home.viewmodel.SimpleVideoViewModel
import kotlinx.coroutines.launch

class HomeDetailCommentFragment : BaseMviLazyFragment<HomeFragmentHomeDetailCommentBinding>() {
    private lateinit var commViewModel: CommentViewModel
    private lateinit var data: SimpleVideoEntity
    override fun handleState() {
        lifecycleScope.launch{
            commViewModel.state.collect{
                when(it){
                    is CommentState.CommentSuccessState ->{showMsg("获得评论成功 ${it.list}")}
                    is CommentState.CommentFailedState -> {showMsg("获得评论失败")}
                    is CommentState.PublishCommentSuccess ->{showMsg("发布评论成功 ${it.entity}")}
                    is CommentState.PublishCommentFailed -> {showMsg("发布评论失败")}
                    is CommentState.PublishComment401Failed ->{showMsg("用户验证不通过")}
                    is CommentState.Init ->{}
                }
            }
        }

    }

    override fun getLayout(): Int {
       return R.layout.home_fragment_home_detail_comment
    }

    override fun initView() {
        super.initView()
        data = arguments?.getParcelable<SimpleVideoEntity>("data") as SimpleVideoEntity
    }

    override fun initData() {
        super.initData()
        //获得评论
        lifecycleScope.launch {
            commViewModel.intents.send(CommentIntent.GetCommentInfo(0,data.id.toString()))
        }
        //发表评论
        lifecycleScope.launch {
            val user = UserUtils.getCurrentUser()
            //commentEntity其实就是json数据
            val commentEntity = CommentEntity(0,"评论的饿信息","",0,0,data.item_id?:"","",
                arrayListOf(),0,user?.id?:0,"")
            commViewModel.intents.send(CommentIntent.PublishComment(commentEntity))
        }

    }
    override fun generateViewModel() {
        commViewModel = ViewModelProvider(this).get(CommentViewModel::class.java)
    }


}